package com.hjb.toolbardemo.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.app_library.utils.CommonCipher;


/**
 * SharedPreferencesUtil
 * 作者: hjb
 * 时间：2016/3/22.
 */
public class SPUtils {
    private static String APP_NAME = "neiquan";
    private static SharedPreferences sp;

    private SPUtils() {
    }

    public static SharedPreferences getSp() {
        if (sp == null) {
            sp = Tools.getContext().getSharedPreferences(APP_NAME, Context.MODE_PRIVATE);
        }
        return sp;
    }

    public static void saveToSP(String key, String valueStr) {
        if (!TextUtils.isEmpty(key) && !TextUtils.isEmpty(valueStr)) {
            SharedPreferences sp = getSp();
            SharedPreferences.Editor editor = sp.edit();
            editor.putString(key, valueStr);
            //提交当前数据
            editor.commit();
        }
    }

    public static String getStringSP(String key, String defaultValue) {
        SharedPreferences sp = getSp();
        return sp.getString(key, defaultValue);
    }

    public static void saveBean(String key, Object o) {
        if (o != null) {
            String s = JSON.toJSONString(o);
            saveByDes(key, CommonCipher.encrypt(CommonCipher.AES_KEY, s));
        }
    }

    private static String getByDes(String key) {
        SharedPreferences sp = getSp();
        String content = sp.getString(key, "");
        return "".equals(content) ? null : CommonCipher.decrypt(CommonCipher.AES_KEY, content);
    }

    private static void saveByDes(String key, String content) {
        if (content != null) {
            SharedPreferences sp = getSp();
            SharedPreferences.Editor editor = sp.edit();
            editor.putString(key, CommonCipher.encrypt(CommonCipher.AES_KEY, content));
            editor.commit();
        }
    }

    public static Object getBean(String key, Class<?> c) {
        String s = getByDes(key);
        if (!TextUtils.isEmpty(s)) {
            return JSON.parseObject(CommonCipher.decrypt(CommonCipher.AES_KEY, s), c);
        }
        return null;
    }
}
